package day02;

import util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestGetPK {

    public static void main(String[] args) {

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con=JdbcUtil.getConnection();
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("insert into t_user ")
                    .append("    (name) ")
                    .append("values ")
                    .append("    (?) ")
                    .toString();

//            ps=con.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
//            ps=con.prepareStatement(sql,new int[]{1});
            ps=con.prepareStatement(sql,new String[]{"id"});

            ps.setString(1,"get3");

            ps.executeUpdate();

            rs=ps.getGeneratedKeys();

            if(rs.next()){
                int id=rs.getInt(1);
                System.out.println("id = " + id);
            }

            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }

    }


}
